#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 1e6 + 10, INF = 0x3f3f3f3f;


void solve()
{
    int n;
    while(cin >> n)
    {
        vector<set<int>> s(n);
        for (int i = 0; i < n; i++) {
            int x; cin >> x;
            for (int j = 0; j < x; j++) {
                int y;cin >> y;
                s[i].insert(y);
            }
        }

        int m;
        cin >> m;
        while (m--) {
            int ans = 0;
            int x, y;
            cin >> x >> y;

            vector<bool> visa(10001), visb(10001);
            visa[x] = visa[y] = visb[x] = visb[y] = true;

            for (int i = 0; i < n; i++)
            {
                if (s[i].count(x))
                {
                    for (auto j : s[i])
                    {
                       visa[j] = true;
                    }
                }
                if (s[i].count(y)) {
                    for (auto j : s[i]) {
                        visb[j] = true;
                    }
                }
            }
            for (int i = 0; i <= 10000; i++)
            {
                if (visa[i] && visb[i]) ans++;
            }
            cout << ans - 2 << "\n";
        }
    }
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    //cin>>T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}